<template>
    <view class="page-content">
        <navbar @clickLeft="toHome" fixed leftIcon="left" title="钱包管理" shadow></navbar>
        <view class="view flex-row ">
            <!-- 预计6月之后才处理切换链
			<view class="w80 bg-d1 " style="height:90vh;">
                <view class="left-bar-item active">
                    <image src="/static/img2/BTC.png" class="image"/>
                </view>
                <view class="left-bar-item" >
                    <image src="/static/img2/EOS.png" class="image"/>
                </view>
                <view class="left-bar-item">
                    <image src="/static/img2/ETH.png" class="image"/>
                </view>
                <view class="left-bar-item">
                    <image src="/static/img2/USDT.png" class="image"/>
                </view>
            </view>-->
            <view class="flex-1  p-l-15 p-r-15 m-t-30" style="overflow-y: auto; max-height:calc(100vh - 400rpx);"  scroll-y="true">
                <!--<view class="bar1-title m-b-12 m-t-15">BNB Chain</view>-->
                
					<view style="background:#f6f6f6;"
						v-for="(item, index) in walletListCopy" :key="index"
						@click="changeDefaultWallet(item.address)"
					>
						<view class="view flex-row align-center justify-between p-l-15 p-r-15 p-t-9 p-b-9 m-b-10 wallet-item" style="border-radius:12px;"
						:class="defaultWallet.address === item.address ? 'wallet-selected' : 'wallet-not-selected'">
							<view>
								<view class="c-1e1 m-b-6 wallet-name">{{item.name}}</view>
								<view class="c-c5c fz-10 address">{{item.address | $hiddenString(5,4)}}</view>
							</view>

							<view class="c-1e1 fz-14 middle">{{item.asset}} CHB</view>
						</view>
						

						<!--<view class="view flex-row align-center justify-between p-l-15 p-r-15 p-t-9 p-b-9 m-b-10 bg-fff" style="border-radius:12px;">
							<view>
								<view class="c-1e1 m-b-6">我的钱包2</view>
								<view class="c-c5c fz-10">0xE2b1******9058</view>
							</view>

							<view class="c-1e1 fz-14">13,000 CHB</view>
						</view>-->
					</view>
                
				<EasyDialog ref="EasyDialog"/>
            </view>
        </view>
        <view class="fix-bottom text-center">
            <el-button  @click="toImportWallet" class="w168 h48" style="font-size:16px; line-height:70rpx;border-radius: 12px !important;">导入钱包</el-button>
            <el-button  @click="toCreateWallet" class="w168 h48"  style="font-size: 16px; line-height:70rpx;border-radius: 12px !important;" type="primary">创建钱包</el-button>
        </view>
    </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import navbar from '@/components/uni-nav-bar'
import elButton from '@/components/el-button/el-button'
import noData from '@/components/noData/noData'
import sibList from '@/components/sib-list/sib-list.vue'

import { isTimeInvalid } from "@/common/tools";
import EasyDialog from "@/components/EasyDialog.vue";
import { BigNumber } from 'bignumber.js';
import walletApi from "@/common/walletApi";
import { aboutWallet } from "@/common/businessCommon";
import _ from "lodash";

import {getTokenBalance} from "@/apis/bsc20.js";

export default {
    components: {
      navbar,
      elButton,
	  EasyDialog
	},
    data() {
        return {
          walletListCopy: [],
        }
    },
	onShow() {
	  
	},
	onLoad() {
		this.getAllWalletAsset();
	},
    computed:{
        ...mapState(['walletList', 'defaultWallet']),
    },
    methods: {
        ...mapMutations(['setWalletList']),
		async changeDefaultWallet(walletAddress){
		    let result = await aboutWallet.setDefaultWallet(walletAddress);
		    if(result.status === 1){
		        this.getAllWalletAsset();
		        this.$refs.EasyDialog.showDialog({
		            title:'提示',
		            text:'更换成功, 该钱包将作为新的默认钱包。',
		            okText:'确定',
		            cancelText:'取消',
		            ok: () => {
		                uni.reLaunch({
		                    url: '/pages/home/index',
		                });
		                //这里返回会出太多不可控问题，强制返回首页
		                //uni.navigateBack();
		            },
		            cancel: () => {
		
		            },
		        });
		    }else{
		        this.$showToast('更换失败');
		    }
		},
		// 获得钱包余额
		async getAllWalletAsset(){
		    uni.showLoading({
		        title: '',
		        mask: true,
		    });
			let web3 = walletApi.web3Init();
		    let walletList = _.cloneDeep(this.walletList);
		    let lastTime = uni.getStorageSync('lastTimeOfGetAllWalletAsset') || 0;
			
			//let address = '0x1090eCB439924FF8DFCA41c653a23927E8850Cb4';
			//let amount = new BigNumber(await web3.eth.getBalance(address));
			//console.log('amount',aboutWallet.toRegularNumber(amount.toString()));
			//console.log('walletList',walletList);
			if(walletList.length > 0){
				walletList.map(async (item) => {
				    if(item.address === this.defaultWallet.address || isTimeInvalid(lastTime, 10*60*1000)){ // 非默认钱包， 30分钟刷新一次
				        let asset = new BigNumber(0);
						let amount = await getTokenBalance(item.address, 'chb');
						console.log('amount',amount,item.address);
						asset = asset.plus(amount.data.amount);
						item.asset = asset;
						//let amount = new BigNumber(await web3.eth.getBalance(item.address));
						//asset = asset.plus(amount);
				        //item.asset = aboutWallet.toRegularNumber(asset.toString());
				    };
				});
			}
		    uni.setStorageSync('lastTimeOfGetAllWalletAsset', new Date().getTime());
		    this.walletListCopy = walletList;
			/*let wl2 = [];
			for(var i=0;  i<100; i++){
			    let thing = [];
				thing.name = 'name'+i;
				thing.asset = i*5;
				thing.address = '23333';
				wl2.push(thing);
			}
			this.walletListCopy = wl2;*/
		    this.setWalletList(walletList);
		    uni.hideLoading();
		},
		toImportWallet(){
		    uni.navigateTo({ url: `/pages/wallet/imporWallet/index`})
		},
		toCreateWallet() {
		    uni.navigateTo({ url: `/pages/wallet/createWallet/index`})
		},
		toHome(){
			uni.reLaunch({
			    url: '/pages/home/index',
			});
			//这里返回会出太多不可控问题，强制返回首页
			//uni.navigateBack();
		}
    }
    
};
</script>

<style lang="scss" scoped>
.bar1-title {
    color:#3C3C3C;
    font-size: 32rpx;
}
page {
    background: #F6F6F6;
}
.left-bar-item {width: 100%;height:68px;display: flex;align-items: center;justify-content: center;}
.left-bar-item .image{
    width:30px;
    height: 30px;
}
.left-bar-item.active {
    background: #F6F6F6;
}
.fix-bottom {width: 100vw;height: 100px;background: #fff;bottom: 0;left: 0;padding-top:32rpx;position: fixed;}
.wallet-list{padding-bottom: 120px;}
.wallet-item{background: #fff;}
.wallet-item.wallet-selected{
		background: #6781FF;
		.wallet-name{
		    color: #fff;
		}
		.address{
			 color: #fff;
		}
		.middle{
			color: #fff;
		}
	}
	.wallet-item-border:last-child{
		margin-bottom: 180rpx;
	}
</style>
